import {
	defineStore
} from 'pinia'
import deviceApi from '@/api/modules/device'

export const useDeviceStore = defineStore('device', {
	state: () => ({
		privateDevices: [],
		publicDevices: [],
		currentDevice: null,
		loading: false
	}),

	actions: {
		// deviceStore.js
		async loadPrivateDevices() {
			this.loading = true;
			try {
				const res = await deviceApi.getUserDevices();
				console.log('从 getUserDevices API 获取到的私有设备列表:', res.data);
				this.privateDevices = res.data || [];
				console.log('已存储的私有设备列表:', this.privateDevices);
				return this.privateDevices;
			} catch (error) {
				console.error('加载私有设备失败:', error);
				uni.showToast({
					title: error.message || '加载失败',
					icon: 'none'
				});
				throw error;
			} finally {
				this.loading = false;
			}
		},
		// 加载用户创建的智能体
		async loadCreatedDevices() {
			return this.loadPrivateDevices()
		},

		async loadPublicDevices(params) {
			this.loading = true;
			try {
				const res = await deviceApi.getPublicDevices(params);
				console.log('从 getPublicDevices API 获取到的公开设备列表:', res.data);
				if (params?.current === 1) {
					this.publicDevices = res.data?.records || [];
				} else {
					this.publicDevices = [...this.publicDevices, ...(res.data?.records || [])];
				}
				console.log('已存储的公开设备列表:', this.publicDevices);
				return res;
			} catch (error) {
				console.error('加载公共设备失败:', error);
				uni.showToast({
					title: error.message || '加载失败',
					icon: 'none'
				});
				throw error;
			} finally {
				this.loading = false;
			}
		},

		// stores/modules/device.js 的 actions 中添加:
		async createDevice(data) {
			this.loading = true;
			try {
				const res = await deviceApi.createDevice(data);
				// After successful creation, reload private devices
				if (res.code === 200) {
					await this.loadPrivateDevices();
				}
				return res;
			} catch (error) {
				console.error('Create device failed:', error);
				throw error;
			} finally {
				this.loading = false;
			}
		},
		// 添加收藏设备的 action
		async collectDevice(deviceId) {
		  if (!deviceId) {
		    throw new Error('设备ID不能为空')
		  }
		  
		  this.loading = true
		  try {
		    const res = await deviceApi.collect(deviceId)
		    // 收藏成功后刷新公开设备列表
		    if (res.code === 200) {
		      await this.loadPublicDevices({ 
		        current: 1,
		        size: 10
		      })
		    }
		    return res  // 返回接口响应
		  } catch (error) {
		    console.error('收藏设备失败:', error)
		    throw error
		  } finally {
		    this.loading = false
		  }
		}
	}
})